﻿using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace Collab.Common
{
    public static class IPUtility
    {
        public static string GetTeredoIPv6Address()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
                return "Network is not available!";

            if (!Socket.OSSupportsIPv6)
                return "localhost";

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

            if (nics == null || nics.Length == 0)
                return "No network interfaces found.";

            foreach (NetworkInterface adapter in nics)
            {
                if (!adapter.Supports(NetworkInterfaceComponent.IPv6))
                    continue;

                if (!adapter.Description.Contains("Teredo"))
                    continue;

                IPInterfaceProperties props = adapter.GetIPProperties();

                foreach (UnicastIPAddressInformation uiai in props.UnicastAddresses)
                {
                    IPAddress addr = uiai.Address;

                    if (addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal)
                        continue;

                    return addr.ToString();
                }
            }
            return "Teredo adapter is not found!";
        }
    }
}
